<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择商品状态" clearable>
          <el-option v-for="dict in dict.type.goods_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:goods:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品图片" align="center" prop="goodsUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodsUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="商品仓库" align="center" prop="warehouseName" />
      <el-table-column label="商品分类" align="center" prop="classifyName" />
      <el-table-column label="商品状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:goods:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商家商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsUrl">
          <image-upload v-model="form.goodsUrl" />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsInfo">
          <el-input v-model="form.goodsInfo" placeholder="请输入商品简介" />
        </el-form-item>
        <el-form-item label="商品状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择商品状态">
            <el-option v-for="dict in dict.type.goods_state" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">商品规格</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="addSpecs">增加商品规格</el-button>
        </el-col>
      </el-row>
      <el-table :data="form.tGoodsSpecsList">
        <el-table-column label="规格名称" align="center" prop="goodsSpecsName">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsSpecsName" placeholder="请输入规格名称" style="width: 100%;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格价格" align="center" prop="goodsSpecsPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsSpecsPrice" placeholder="请输入规格价格" style="width: 100%;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格库存" align="center" prop="goodsSpecsNum">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsSpecsNum" placeholder="请输入规格库存数量" style="width: 100%;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delSpecsData(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider content-position="center">商品分类</el-divider>
      <el-table :data="classifyList" row-key="id" :tree-props="{ children: 'children' }" :default-expand-all="true"
        :expand-on-click-row="false" @row-click="selectChild" highlight-current-row>
        <!-- 选择框列 -->
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column label="" width="80" align="center">
          <template slot-scope="scope">
            <!-- 只有当存在子类且子类不为空时才显示单选框 -->
            <el-radio v-removeAriaHidden v-if="!scope.row.children" v-model="form.classifyId"
              :label="scope.row.id">{{ '' }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="分类id" align="center" prop="id" />
        <el-table-column label="分类名" align="center" prop="classifyName" />
        <!-- <el-form-item label="分类名" prop="classifyName"></el-form-item> -->
      </el-table>
      <pagination v-show="classifyTotal > 0" :total="classifyTotal" :page.sync="classifyQuery.pageNum"
        :limit.sync="classifyQuery.pageSize" @pagination="getClassifyList"/>
        
      <el-divider content-position="center">仓库信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-input v-model="wareHouseQuery.warehouseName" placeholder="请输入仓库名称" />
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-search" @click="searchWareHouse">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" @click="resetWareHouseQuery">重置</el-button>
        </el-col>
      </el-row>
      <el-table :data="wareHouseList" @row-click="selectWarehouse" highlight-current-row>
        <el-table-column label="" width="55" align="center">
          <template slot-scope="scope">
            <el-radio v-removeAriaHidden v-model="form.warehouseId" :label="scope.row.warehouseId">{{ '' }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="仓库id" align="center" prop="warehouseId" />
        <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      </el-table>
      <pagination v-show="wareHouseTotal > 0" :total="wareHouseTotal" :page.sync="wareHouseQuery.pageNum"
        :limit.sync="wareHouseQuery.pageSize" @pagination="getWarehouse" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/business/goods";
import { listWarehouse } from "@/api/business/warehouse";
import { tableClassify } from "@/api/classify/classifyMain";

export default {
  name: "Goods",
  dicts: ['goods_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandId: JSON.parse(localStorage.getItem("store")).storeId,
        goodsName: null,
        state: null,
      },
      // 表单参数
      form: {
        goodsId: null,
        goodsName: null,
        brandId: JSON.parse(localStorage.getItem("store")).storeId,
        goodsUrl: null,
        goodsPrice: null,
        goodsInfo: null,
        state: null,
        tGoodsSpecsList: [{
          goodsSpecsName: "",
          goodsSpecsPrice: "",
          goodsSpecsNum: ""
        }]
      },
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        goodsUrl: [
          { required: true, message: "请上传至少一张商品图片", trigger: "change" }
        ],
        goodsPrice: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "请选择商品状态", trigger: "change" }
        ]
      },
      wareHouseQuery: {
        pageNum: 1,
        pageSize: 10,
        storeId: JSON.parse(localStorage.getItem("store")).storeId,
        warehouseName: null,
        areasId: null,
      },
      wareHouseTotal: 0,
      wareHouseList: [],
      goodsSpecs: [],
      classifyQuery: {
        pageNum: 1,
        pageSize: 10,
        classifyName: null
      },
      classifyList: [],
      classifyTotal: 0
    };
  },
  created() {
    // console.log(JSON.parse(localStorage.getItem("store")).storeId)
    this.getList();
    this.getWarehouse();
    this.getClassifyList();
  },
  methods: {
    selectChild(row){
      if(!row.children){
        this.form.classifyId = row.id
      }
      // this.$set(this.form, 'classifyTwoId', row.id)
    },
    getClassifyList() {
      tableClassify(this.classifyQuery).then(response => {
        this.classifyList = response.rows;
        this.classifyTotal = response.total;
      });
    },
    delSpecsData(item) {
      this.form.tGoodsSpecsList.splice(this.form.tGoodsSpecsList.indexOf(item), 1)
    },
    addSpecs() {
      this.form.tGoodsSpecsList.push({
        goodsSpecsName: "",
        goodsSpecsPrice: "",
        goodsSpecsNum: ""
      })
    },
    searchWareHouse() {
      this.wareHouseQuery.pageNum = 1;
      this.getWarehouse();
    },
    resetWareHouseQuery() {

    },
    selectWarehouse(row) {
      this.$set(this.form, 'warehouseId', row.warehouseId)
      // this.form.warehouseId = row.warehouseId
      // console.log(this.form)
    },
    getWarehouse() {
      listWarehouse(this.wareHouseQuery).then(response => {
        this.wareHouseList = response.rows;
        this.wareHouseTotal = response.total;
      })
    },
    /** 查询商家商品管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsName: null,
        brandId: JSON.parse(localStorage.getItem("store")).storeId,
        goodsUrl: null,
        goodsPrice: null,
        goodsInfo: null,
        state: null,
        tGoodsSpecsList: [{
          goodsSpecsName: "",
          goodsSpecsPrice: "",
          goodsSpecsNum: ""
        }]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品:"+row.goodsId+" "+row.goodsName;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tGoodsSpecsList.length != 0) {
            console.log(this.form)
            let flag = true
            this.form.tGoodsSpecsList.forEach(item => {
              for (const key in item) {
                if (key == "createBy" || key == "createTime" || key == "remark" || key == "updateBy" || key == "updateTime") {
                  continue;
                }
                if (item[key] == "" || item[key] == null) {
                  flag = false
                }
              }
            })
            if (!flag) {
              this.$modal.msgError("请完善商品规格信息！")
              return
            }
          }else if (this.form.tGoodsSpecsList.length == 0 || this.form.tGoodsSpecsList==null) {
            this.$modal.msgError("请填加至少一项商品规格信息！")
            return
          }
          if (this.form.warehouseId == null || this.form.classifyTwoId == '') {
            this.$modal.msgError("请选择仓库");
            return;
          }
          if(this.form.classifyId == null || this.form.classifyId == ''){
            this.$modal.msgError("请选择商品分类");
            return
          }
          // this.form.brandId=JSON.parse(localStorage.getItem("store")).storeId
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除商品id："' + goodsIds + '" 的商品？').then(function () {
        return delGoods(goodsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
